import { useRouter } from '@/hooks';
import { isObject, appendQuery, trimEnd, isHttp, trimStart, cache } from './index';
import Taro from '@tarojs/taro';
import { HOST } from './config';
import { catchError } from './request';

export default function Upload(baseURL) {
  const router = useRouter();
  baseURL = HOST.value + baseURL;

  function doUpload(url, filePath, options) {
    return new Promise((resolve, reject) => {
      let { header, params, name, data, onProgress } = options;
      const token = cache.get('token');
      const defaultHeader = {
        Accept: 'application/json',
        Authorization: token ?? ''
      };

      if (isObject(params)) {
        url = appendQuery(url, params);
      }
      if (isObject(header)) {
        Object.assign(defaultHeader, header);
      }
      if (isHttp(baseURL) && !isHttp(url)) {
        url = `${trimEnd(baseURL, '/')}/${trimStart(url, '/')}`;
      }
      Taro.uploadFile({
        url,
        filePath,
        name,
        header: defaultHeader,
        formData: data,
        success(response) {
          if (response.statusCode == 200) {
            if (typeof response.data == 'string') response.data = JSON.parse(response.data);
            resolve(response.data);
          } else {
            console.error(response);
            reject({
              code: 500,
              message: '服务器响应失败'
            });
          }
        },
        fail(err) {
          console.error(err);
          reject({
            code: 500,
            message: '服务器响应失败'
          });
        }
      }).onProgressUpdate(even => {
        onProgress?.call(null, even);
      });
    }).then(data => catchError(data, router));
  }

  return function (url, filePath, config = {}) {
    let defaults = {
      name: 'file',
      data: {},
      header: {},
      onProgress: e => {
        console.log('onProgress', e);
      },
      ...config
    };
    return doUpload(url, filePath, defaults);
  };
}
